package gu.sql2java.geometry.jackson;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.google.common.base.Strings;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

/**
 * Deserialize WKT property as Geometry Object with Jackson<br>
 * @author guyadong
 * @param <T>
 * @since 3.18.0
 */
public class GeometryDeserializer<T extends Geometry> extends JsonDeserializer<T> {

    @SuppressWarnings("unchecked")
    @Override
    public T deserialize(JsonParser jp, DeserializationContext ctxt)
           throws IOException, JsonProcessingException {
        try {
            String text = jp.getValueAsString();
            if(Strings.isNullOrEmpty(text)) {
                return null;
            }
            WKTReader reader = new WKTReader();
            return (T) reader.read(text);
        } catch (ParseException e) {
           throw new IOException(e);
        }
    }
}
